package com.h3bpm.web.login;

import OThinker.Common.DotNetToJavaStringHelper;
import OThinker.Common.Organization.Models.User;
import OThinker.Common.Organization.enums.PrivacyLevel;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Mobile.Controller.MobileAccess;
import com.h3bpm.base.user.UserValidator;
import com.h3bpm.base.util.Sessions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: VillWang
 * @Date: 2020/6/1 14:46
 */
@RestController
@RequestMapping("/Portal/Login")
public class LonginController  extends ControllerBase {
    /**
     * @Fields serialVersionUID :
     */
    private static final long serialVersionUID = 1951305555362177857L;
    /**
     * @Title: ValidateLoginForDingTalk
     * @Description: 钉钉集成登录
     * @Param: @param state
     * @Param: @param code
     * @Param: @return
     * @Return: Object
     * @throws Exception
     */
    @RequestMapping(value="/ValidateLogin",method= RequestMethod.GET)
    @ResponseBody
    public Object ValidateLoginForDingTalk(HttpServletRequest request, HttpServletResponse response, String state, String code) throws InstantiationException, IllegalAccessException, Exception{
        User currentUser = null;
        UserValidator userValidator = null;
        String userImage = "";
        // 钉钉登录
        userValidator = UserFactory.LoginAsDingTalkReturnUserValidator(request,state, code);
        Map<String, Object> result = new HashMap<String, Object>();
        if (userValidator == null){
            result.put("Success", false);
        } else {
            currentUser = userValidator.getUser();

            userImage = userValidator.getImagePath();
            MobileAccess mobile = new MobileAccess();
            MobileAccess.MobileUser mobileUser = mobile.GetMobileUser(userValidator, currentUser, userImage, "", "");
            //update by ouyangsk 获取用户当前父部门
            result.put("DirectoryUnits", mobileUser == null ? null : GetDirectoryUnits(mobileUser.getObjectID(), null));
            result.put("Success", true);
            result.put("PortalRoot",  this.GetPortalRoot());
            result.put("MobileUser", mobileUser);

            if(request.getSession().getAttribute(currentUser.getCode())==null){
                Cookie cookies = new Cookie(currentUser.getCode(),"false");
                cookies.setMaxAge(3600);
                response.addCookie(cookies);
                request.getSession().setAttribute(currentUser.getCode(), cookies);
            }
            // 当前用户登录
            request.getSession().setAttribute(Sessions.GetUserValidator(), userValidator);
            request.getSession().setAttribute(Sessions.GetDingTalkLogin(), true);
            //update by ouyangsk 移动端登陆后设置session不过期
            request.getSession().setMaxInactiveInterval(0);
        }
        return result;
    }

    /**
     * @Title: GetPortalRoot
     * @Description: 获取根虚拟目录
     * @Param: @return
     * @Return: Object
     * @throws
     */
    public String GetPortalRoot(){
        return this.getPortalRoot();
    }

    /**
     获取移动办公用户对象

     @param sourceUser 获取信息的用户
     @param user 被获取的用户
     @param imageUrl
     @param departmentName
     @param mobileToken
     @return
      * @throws Exception
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    @RequestMapping(value="/GetMobileUser",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public final MobileAccess.MobileUser GetMobileUser(UserValidator sourceUser, User user, String imageUrl, String departmentName, String mobileToken) throws InstantiationException, IllegalAccessException, Exception
    {
        String mobile, officePhone, email, code, wechat;
        mobile = officePhone = email = code = wechat = "";

        if (user.getPrivacyLevel() == PrivacyLevel.PublicToAll
                || (sourceUser != null && user.getPrivacyLevel() == PrivacyLevel.PublicToDept && user.getParentID() == sourceUser.getUser().getParentID())
                || (sourceUser != null && user.getPrivacyLevel() == PrivacyLevel.PublicToDepts && getEngine().getOrganization().IsAncestor(user.getParentID(), sourceUser.getUser().getParentID()))
                || (sourceUser != null && user.getPrivacyLevel() == PrivacyLevel.Confidential && sourceUser.ValidateOrgView(user.getObjectID())))
        {
            mobile = user.getMobile();
            officePhone = user.getOfficePhone();
            email = user.getEmail();
            code = user.getCode();
            wechat = user.getWeChatAccount();
        }
        //update by zhengyj 处理用户头像
        imageUrl = UserValidator.GetUserImagePath(getEngine(), user, this.getPortalRoot()+"/TempImage/").replace("//", "/");
        if(!DotNetToJavaStringHelper.isNullOrEmpty(imageUrl)){
            imageUrl = "/"+ imageUrl+"?T="+(new Date()).getTime();
        }
        MobileAccess.MobileUser tempVar = new MobileAccess.MobileUser();
        tempVar.setObjectID(user.getObjectID());
        tempVar.setName(user.getName());
        tempVar.setCode(user.getCode());
        tempVar.setAppellation(user.getAppellation());
        tempVar.setDepartmentName(departmentName);
        tempVar.setEmail(email);
        tempVar.setMobile(mobile);
        tempVar.setImageUrl(imageUrl);
        tempVar.setOfficePhone(officePhone);
        tempVar.setWeChat(wechat);
        tempVar.setMobileToken(mobileToken);
        //update by ouyangsk
        tempVar.setGender(user.getGenderInt());
        MobileAccess.MobileUser mobileUser = tempVar;
        return mobileUser;
    }

    @Override
    public String getFunctionCode() {
        return null;
    }
}
